<template>
  <div>
    <!-- 任务列表 -->
    <div class="tabNav">
      <router-link to="/index">
        <img :src="require('/src/assets/img/sidebar1.png')" />首页
      </router-link>
      <b class="colors"
        >/<img :src="require('/src/assets/img/renwujianying.png')" />任务管理</b
      >
      <b><span class="fenge">/</span>任务列表</b>
    </div>
    <el-card class="cardTits" shadow="hover">
      <div class="subject-title">
        <div class="query query-task">
          <div class="flex-box">
            <div class="query-input">
              <el-input
                placeholder="ID/任务名称"
                v-model="searchVal"
              ></el-input>
            </div>
            <div class="query-select">
              <el-select v-model="selectValue" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
            <el-button class="query-btn" @click="getTaskList" type="primary">查询</el-button>
          </div>
          <el-button
            @click="addTaskModule = true"
            class="query-btn task-add"
            icon="el-icon-plus"
            >新建</el-button
          >
        </div>
        <div class="download" v-show="checkedLsit.length > 0">
          <span @click="enableTask(checkedLsit)">启用</span>
          <span @click="updateTaskStatus(checkedLsit)">禁用</span>
          <span @click="deleteTask(checkedLsit)">删除</span>
        </div>
      </div>
      <el-table
        :data="tableData"
        @selectionChange="downloadWhether"
        stripe
        style="width: 100%"
        ref="multipleTable"
        :row-key="getRowKeys"
        @sort-change="sortChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="60"> </el-table-column>
        <el-table-column prop="id" sortable="custom" label="任务ID" width="100"> </el-table-column>
        <el-table-column prop="name" sortable="custom" label="任务名称" width="">
        </el-table-column>
        <el-table-column prop="taskPayment" sortable="custom" align="center" label="预估服务费" min-width="110">
          <template #default="item">
            {{ formatNumber(item.row.taskPayment) }}
          </template>
        </el-table-column>
        <el-table-column prop="needPeopleNum" sortable="custom" align="center" label="发放人数" width=""></el-table-column>
        <el-table-column prop="releaseDate" sortable="custom" label="任务开始时间" min-width="110">
          <template #default="item">
            {{ format("yyyy-MM-dd", new Date(item.row.releaseDate)) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" sortable="custom" label="任务结束时间" min-width="110">
          <template #default="item">
            {{ format("yyyy-MM-dd", new Date(item.row.endDate)) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" sortable="custom" label="任务创建时间" min-width="110">
          <template #default="item">
            {{ format("yyyy-MM-dd", new Date(item.row.createTime)) }}
          </template>
        </el-table-column>
        <el-table-column prop="isDisable" align="center" label="状态" width="">
          <template #default="item">
            {{ isDisable[item.row.isDisable] }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          class-name="editor"
          width="200"
          align="center"
        >
          <template #default="item">
            <el-button @click="updateTaskStatus([item.row.id])" v-if="item.row.isDisable == 1" type="text">禁用</el-button>
            <el-button @click="enableTask([item.row.id])" v-else type="text">启用</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button @click="getTaskDetails(item.row.id)" type="text">详情</el-button>
            <el-divider direction="vertical"></el-divider>
            <router-link
              :to="{
                name: 'ReceiveDetails',
                query: { id: item.row.id },
              }"
            >
              <el-button type="text">明细</el-button>
            </router-link>
            <el-divider direction="vertical"></el-divider>
            <el-button  @click="deleteTask([item.row.id])" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="tableData.length > 0"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="arrPage"
        :page-size="selectPage"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 新建弹出层 -->
    <el-dialog title="新建任务" custom-class="task-margin" v-model="addTaskModule" @close="taskClose" width="600px">
      <div class="add-task">
        <el-form
          :model="taskForm"
          :rules="rules"
          v-if="addTaskModule"
          ref="taskForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="taskForm.name"></el-input>
          </el-form-item>
          <el-form-item label="预估服务费" prop="taskPayment">
            <el-input v-model="taskForm.taskPayment"></el-input>
            <div style="line-height: 18px;font-size: 12px; margin-top: 6px;color: #949494;">tips：实际服务费最终与服务者输出的劳动成果有关，可能会与预估服务费有偏差，请以企业验收后的实际服务费为准。</div>
          </el-form-item>
          <el-form-item label="发起方式">
            <el-radio-group v-model="taskForm.launchMode">
              <el-radio label="1">所有关注企业的人</el-radio>
              <el-radio label="2">部分关注企业的人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上传人员表" style="overflow:hidden" v-show="taskForm.launchMode == 2">
            <el-upload
              class="upload-renyuanbiao"
              action="#"
              :multiple="false"
              :limit="1"
              :auto-upload="false"
              accept="xlsx"
              :file-list="fileList"
              :on-change="xlsxFilelist"
              :on-remove="deleteXlsxfile"
            >
              <el-button size="small" plain>点击上传Excel名单</el-button>
            </el-upload>
            <el-button @click="downloadBatchTCheckTemplate" class="query-plain" plain>
              <i class="el-icon-upload"></i>
              下载上传模板
            </el-button>
          </el-form-item>
          <div class="cardTits renwu-error" v-if="mubanflag">
            <div class="renwu-title">数据问题：</div>
            <el-table
              :data="mubanArr"
              stripe
              max-height="200"
              style="width: 100%"
            >
              <el-table-column prop="name" label="姓名"></el-table-column>
              <el-table-column prop="idCard" min-width="150" label="身份证号"></el-table-column>
              <el-table-column prop="reason" label="原因"></el-table-column>
            </el-table>
            <span class="renwu-dwoload" @click="loadfile">异常人员名单下载</span>
          </div>
          <el-form-item label="任务开始时间" required>
            <el-form-item prop="releaseDate">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                :disabledDate="disabledStartTime"
                v-model="taskForm.releaseDate"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="任务结束时间" required>
            <el-form-item prop="endDate">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                :disabledDate="disabledEndTime"
                v-model="taskForm.endDate"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-form-item>
          <el-form-item label="任务地址" prop="taskAddress">
            <el-input v-model="taskForm.taskAddress"></el-input>
          </el-form-item>
          <el-form-item label="任务说明" prop="taskDescription">
            <el-input type="textarea" v-model="taskForm.taskDescription"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addTaskModule = false">取 消</el-button>
          <el-button type="primary" @click="addTaskMethods"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹出层 -->
    <el-dialog title="详情" v-model="detailsTaskModule" width="600px">
      <div class="details-task" v-if="Object.keys(taskDetailsObj).length > 0">
        <el-form
          :model="taskForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-form-item label="任务名称" prop="name">
            <div class="task-content">{{ taskDetailsObj.name }}</div>
          </el-form-item>
          <el-form-item label="任务服务款">
            <div class="task-content">{{ taskDetailsObj.taskPayment }}</div>
          </el-form-item>
          <el-form-item label="发起方式">
            <div class="task-content">{{ taskDetailsObj.launchMode == 1 ? '所有关注企业的人' : '部分关注企业的人' }}</div>
          </el-form-item>
          <el-form-item label="任务开始时间">
            <div class="task-content">{{ format("yyyy-MM-dd", new Date(taskDetailsObj.releaseDate)) }}</div>
          </el-form-item>
          <el-form-item label="任务结束时间">
            <div class="task-content">{{ format("yyyy-MM-dd", new Date(taskDetailsObj.endDate)) }}</div>
          </el-form-item>
          <el-form-item label="任务地址">
            <div class="task-content">{{ taskDetailsObj.taskAddress }}</div>
          </el-form-item>
          <el-form-item label="任务说明">
            <div class="task-content">{{ taskDetailsObj.taskDescription }}</div>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="detailsTaskModule = false">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: "ListTask",
  data() {
    return {
      getRowKeys(row) {
        // 获取row的key值
        return row.id;
      },
      orderByZH: false,
      orderByAsc: false,
      orderByColume: 'createTime',
      mubanflag: false,
      mubanArr: [],
      mubanUrl: "",
      searchVal: "", // 查询条件
      total: 1, // 总条数
      arrPage: [10, 20], // 每页条数
      selectPage: 10, // 每页选中条数
      currentPage: 1,
      isDisable: { // 任务状态
        1: '已启用',
        0: '已禁用',
      },
      options: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "1",
          label: "已启用",
        },
        {
          value: "0",
          label: "已禁用",
        },
      ],
      selectValue: "",
      tableData: [],
      addTaskModule: false,
      taskForm: {
        name: "", // 任务名称
        taskPayment: "", // 服务款
        launchMode: "1", // 发起方式
        releaseDate: "", // 任务开始时间
        endDate: "", // 任务结束时间
        taskAddress: "", // 任务地址
        taskDescription: "", // 任务说明
      },
      rules: {
        name: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
        taskPayment: [
          { required: true, message: "请输入任务服务款", trigger: "blur" },
        ],
        releaseDate: [
          {
            type: "date",
            required: true,
            message: "请选择任务开始日期",
            trigger: "change",
          },
        ],
        endDate: [
          {
            type: "date",
            required: true,
            message: "请选择任务结束时间",
            trigger: "change",
          },
        ],
        taskAddress: [
          { required: true, message: "请输入任务地址", trigger: "blur" },
        ],
        taskDescription: [
          { required: true, message: "请填写任务说明", trigger: "blur" },
        ]
      },
      fileList: [],
      checkedLsit: [],
      detailsTaskModule: false,
      taskDetailsObj: {}
    };
  },
  components: {},
  activated() {
    this.getTaskList()
  },
  methods: {
    disabledStartTime(time) {
      // 设置日期范围
      let dateTime = new Date(this.taskForm.endDate);
      let endDateTime = dateTime.setDate(dateTime.getDate());
      return (
        time.getTime() > new Date(endDateTime).getTime()
      );
    },
    disabledEndTime(time) {
      // 设置日期范围
      let dateTime = new Date(this.taskForm.releaseDate);
      let startDateTime = dateTime.setDate(dateTime.getDate());
      return (
        new Date(startDateTime).getTime() > time.getTime()
      );
    },
    downloadBatchTCheckTemplate() {
      // 下载上传模板
      let info = JSON.parse(localStorage.getItem("bussines_info"))
      axios({
        method: "GET",
        url: "/api/quick/task/manage/downloadTaskSevicerTemplate",
        responseType: "blob",
        headers: {
          "websiteName": window.location.host,
          "Authorization": localStorage.getItem("bussines_token"),
          "businessId": info.businessId,
          "businessNo": info.businessNo,
          "platformId": info.platformId,
          "platformNo": info.platformNo,
          "businessType": 3
        }
      })
      .then((res) => {
        const blob = new Blob([res.data]);
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        //后台再header中传文件名
        downloadElement.href = href;
        downloadElement.download = "上传模板.xlsx"
        document.body.appendChild(downloadElement);
        downloadElement.click();
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      })
      .catch((err) => {
        console.log(err);
      });
    },
    downloadWhether(d) {
      // 表格复选 选择回调
      this.checkedLsit = []
      for(let i = 0; i<d.length; i++) {
        this.checkedLsit.push(d[i].id)
      }
    },
    handleCurrentChange(d) {
      // 分页切换回调
      this.currentPage = d
      this.getTaskList()
    },
    handleSizeChange(d) {
      // 分页切换每页条数回调
      this.selectPage = d
      this.getTaskList()
    },
    getTaskList() {
      // 获取列表信息
      this.$http({
        url: "/api/quick/business/task/selectTasks",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          mixedStr: this.searchVal,
          isDisable: this.selectValue,
          pageNum: this.currentPage,
          pageSize: this.selectPage,
          orderByAsc: this.orderByAsc, // 是否正序
          orderByColume: this.orderByColume, // 排序字段
          orderByZH: this.orderByZH, // 是否汉字
        },
      }).then((data) => {
        if (data.code == 0) {
          this.tableData = data.result.list
          this.total = data.result.total
        }
      });
    },
    sortChange(d) {
      // 监听排序
      if(d.prop == null) {
        // 默认排序方式
        this.orderByZH = false
        this.orderByAsc = false
        this.orderByColume = 'createTime'
      }else {
        let orderByZH = false
        if(d.prop == "name") {
          orderByZH = true
        }
        this.currentPage = 1
        this.selectPage = 10
        let orderByAsc = d.order == "descending" ? false : true
        this.orderByZH = orderByZH
        this.orderByAsc = orderByAsc
        this.orderByColume = d.prop
      }
      this.getTaskList()
    },
    updateTaskStatus(id) {
      // 禁用
      this.$confirm('是否禁用任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'task-message',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: "/api/quick/business/task/disabledTask",
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: id,
        }).then((data) => {
          if (data.code == 0) {
            this.$message({
              message: '已禁用',
              type: 'success',
              offset: 60
            })
            this.getTaskList()
          }
        });
      }).catch(() => {
      });
    },
    enableTask(id) {
      // 任务启用
      this.$confirm('是否启用任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'task-message',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: "/api/quick/business/task/enableTask",
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: id,
        }).then((data) => {
          if (data.code == 0) {
            this.$message({
              message: '已启用',
              type: 'success',
              offset: 60
            })
            this.getTaskList()
          }
        });
      }).catch(() => {
      });
    },
    deleteTask(id) {
      // 任务删除
      this.$confirm('是否删除任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass: 'task-message',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: "/api/quick/business/task/deleteTask",
          method: "post",
          headers: {
            "Content-Type": "application/json",
          },
          data: id,
        }).then((data) => {
          if (data.code == 0) {
            this.$message({
              message: '已删除',
              type: 'success',
              offset: 60
            })
            this.getTaskList()
          }
        });
      }).catch(() => {
      });
    },
    xlsxFilelist(file) {
      this.fileList = [file]
    },
    deleteXlsxfile() {
      this.fileList = []
    },
    addTaskMethods() {
      // 新建任务
      if(this.taskForm.launchMode == 2 && this.fileList.length == 0) {
        this.$message({
          message: '请选择上传人员列表',
          type: 'error',
          offset: 60
        })
        return false
      }
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          let file = new FormData()
          if(this.taskForm.launchMode == 2) {
            file.append("file", this.fileList[0].raw)
          }
          file.append("reqDto", JSON.stringify(this.taskForm))
          let d = this.format('yyyy-MM-dd', this.taskForm.endDate)
          this.taskForm.endDate = new Date(d + ' 23:59:59')
          this.$http({
            url: "/api/quick/task/manage/createBusinessTask",
            method: "post",
            headers: {
              "Content-Type": "multipart/form-data",
            },
            data: file
          }).then((data) => {
            if (data.code == 0) {
              if(data.result == null || data.result.data.length == 0) {
                this.addTaskModule = false
                this.$message({
                  message: '新建任务成功',
                  type: 'success',
                  offset: 60
                })
                this.taskForm = {
                  name: "", // 任务名称
                  taskPayment: "", // 服务款
                  launchMode: "1", // 发起方式
                  releaseDate: "", // 任务开始时间
                  endDate: "", // 任务结束时间
                  taskAddress: "", // 任务地址
                  taskDescription: "", // 任务说明
                }
                this.getTaskList()
              }else {
                this.$message({
                  message: '新建任务失败！人员表数据异常！',
                  type: 'error',
                  offset: 60
                })
                this.mubanArr = data.result.data
                this.mubanflag = true
                this.mubanUrl = data.result.url
              }
            }
          });
        } else {
          return false;
        }
      });
    },
    getTaskDetails(id) {
      // 获取任务详情
      this.$http({
        url: "/api/quick/business/task/selectTaskDetail",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        data: {
          taskId: id
        },
      }).then((data) => {
        if (data.code == 0) {
          this.taskDetailsObj = data.result
          this.detailsTaskModule = true
        }
      });
    },
    loadfile() {
      window.open(this.mubanUrl)
    },
    taskClose() {
      // 关闭新建任务清除数据
      this.mubanUrl = ""
      this.mubanflag = false
      this.mubanArr = []
      this.taskForm = {
        name: "", // 任务名称
        taskPayment: "", // 服务款
        launchMode: "1", // 发起方式
        releaseDate: "", // 任务开始时间
        endDate: "", // 任务结束时间
        taskAddress: "", // 任务地址
        taskDescription: "", // 任务说明
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.el-input--prefix .el-input__inner {
    padding-left: 30px !important;
}
.query-task {
  justify-content: space-between;
  .flex-box {
    display: flex;
  }
  .task-add {
    margin-right: 20px;
    & :deep(span),
    & :deep(i) {
      color: #ffffff;
    }
  }
}
.add-task {
  padding-right: 50px;
  & :deep(.el-form-item) {
    .el-date-editor--date {
      .el-input__inner {
        padding: 0 30px;
      }
    }
  }
  & :deep(.el-upload--text) {
    width: auto;
    height: auto;
    border: 0;
    display: block;
    text-align: left;
  }
  & :deep(.el-button--small) {
    color: #326CF0;
    border-color: #326CF0;
  }
}

.details-task {
  .task-content {
    color: #0A2E6A;
  }
  & :deep(.el-form-item) {
    .el-form-item__label,
    .el-form-item__content {
      line-height: 22px;
    }
  }
}
.task-message {
  width: 260px;
  text-align: left;
  .el-button--primary {
    background-color: #326CF0;
    color: #ffffff;
  }
}
.query-plain {
  float: right;
  margin-top: 3px;
}
.el-form-item__content .upload-renyuanbiao {
  float: left;
  margin-left: 0;
  width: auto !important;
}
.cardTits.renwu-error {
  margin-left: 152px;
  margin-bottom: 20px;
  .renwu-title {
    margin-bottom: 10px;
  }
  .el-table {
    th {
      height: 40px;
    }
  }
  .renwu-dwoload {
    color: #326CF0;
    margin-top: 10px;
    font-size: 12px;
    display: inline-block;
    cursor: pointer;
  }
  .renwu-dwoload:hover {
    text-decoration: underline;
  }
}
.task-margin {
  margin-bottom: 100px;
}
</style>